package com.elephant.core.utils;

import com.alibaba.fastjson.JSONObject;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author: hai
 * @Date: 2019/1/10 10:47
 */
public class ValidatorUtils {

    private static Validator fastValidator = Validation.byProvider(HibernateValidator.class)
            .configure()
            .failFast(true)
            .buildValidatorFactory()
            .getValidator();

    public static <T> ValidatorResult validateResult(T t){
        Set<ConstraintViolation<T>> constraintViolations = fastValidator.validate(t);
        return getValidatorResult(constraintViolations);
    }

    private static <T> ValidatorResult getValidatorResult(Set<ConstraintViolation<T>> constraintViolations) {
        if(constraintViolations.isEmpty()){
            return ValidatorResult.access();
        }

        Map<String,String> map = new HashMap<>(16);

        for (ConstraintViolation<T>
                constraintViolation : constraintViolations) {
            String prop = constraintViolation.getPropertyPath().toString();
            if(map.containsKey(prop)){
                String val = map.get(prop);
                val = val.concat("|").concat(constraintViolation.getMessage());
                map.put(prop,val);
            }else{
                map.put(prop,constraintViolation.getMessage());
            }
        }
        ValidatorResult result = new ValidatorResult();
        result.setAccess(false);
        result.setMessage(JSONObject.toJSONString(map,true));

        return result;
    }
}
